﻿using Database;
using DSkin.DirectUI;
using DSkin.Forms;
using DSkinTheme.Helper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DSkinTheme
{
    public partial class FrmMain : DSkin.Forms.DSkinForm
    {
        private int MType = 1;
        /// <summary>
        /// 账号信息表
        /// </summary>
        private string MTableName = "Users";


        public static int WM_CLIPBOARDUPDATE = 0x031D;
        [DllImport("user32.dll")]
        public static extern bool AddClipboardFormatListener(IntPtr hwnd);
        [DllImport("user32.dll")]
        public static extern bool RemoveClipboardFormatListener(IntPtr hwnd);

        string mpicPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/MPic/";
        DbAccess db;
        public FrmMain()
        {
            //链接数据库，如果数据库不存在自动创建
            db = new DbAccess(mpicPath + "MPic.db");

            var isExists = db.IsCreateTable(MTableName);
            if (!isExists)
            {
                //创建表，它包含有 TEXT类型 的 name 列  和 INTEGER类型 的 id 列
                db.CreateTable(MTableName, new string[] { "BucketName", "AccessKey", "SecretKey", "Domain", "Type" }, new DataType[] { DataType.TEXT, DataType.TEXT, DataType.TEXT, DataType.TEXT, DataType.INTEGER });
            }
            //添加剪切板监听
            AddClipboardFormatListener(Handle);
            InitializeComponent();
            switchImage1.AddImageItems(@"E:\框架\DSkin\自定义\DSkinTheme\DSkinTheme\Resources\test1.png", "广告位招租(1周/199块)", Color.Red, false);
            //switchImage1.AddImageItems(@"http://file.lzhaofu.cn/1218/20181219/AeugjmGzwoVc.png", "广告位招租(1周/199块)", Color.Red, true);
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            #region 窗体显示特效

            //自定义特效
            Opacity = 0;
            Rectangle rect = Screen.PrimaryScreen.WorkingArea;

            int top = (rect.Height - Height) / 2;
            Location = new Point(rect.Width - Width, top);
            int centerLeft = (rect.Width - Width) / 2;

            DoEffect(() =>
            {
                if (Left > centerLeft + 4)
                {
                    Opacity = 1 - 1.0 * (Left - centerLeft) / (rect.Width - Width - centerLeft);
                    Left -= ((Left - centerLeft) / 5);
                    return true;
                }
                Opacity = 1;
                ShowShadow = true;
                return false;
            });

            #endregion
        }


        Image pic = Image.FromFile(@"F:\logo\新鴻蒙.png");
        private void ListBox_Load(object sender, EventArgs e)
        {

            for (int i = 0; i < 10; i++)//添加列表项目
            {
                DuiPictureBox picBox = new DuiPictureBox();//图片容器
                picBox.Size = new Size(120, 120);
                //picBox.BackColor = Color.Red;
                picBox.Location = new Point(5, 5);
                //picBox.MouseEnter += picBox_MouseEnter;//绑定事件实现鼠标移入移出的边框变化效果
                //picBox.MouseLeave += picBox_MouseLeave;
                picBox.Borders.BottomWidth = 3;
                picBox.Borders.LeftWidth = 3;
                picBox.Borders.RightWidth = 3;
                picBox.Borders.TopWidth = 3;
                picBox.Image = pic;//设置图片
                picBox.SizeMode = PictureBoxSizeMode.StretchImage;

                DuiBaseControl item = new DuiBaseControl();//列表项目
                item.Size = new Size(200, 200);
                item.Top = 10;
                item.Controls.Add(picBox);

                dSkinListBox2.Items.Add(item);
            }
            dSkinListBox2.LayoutContent();
        }

        /// <summary>
        /// 设置DSkinComboBox里的Item的样式
        /// </summary>
        /// <param name="comboBox"></param>
        public void SetComboBoxTheme(DSkin.Controls.DSkinComboBox comboBox)
        {
            comboBox.InnerListBox.Borders.AllColor = Color.FromArgb(196, 196, 196);
            foreach (DSkin.DirectUI.DuiLabel item in comboBox.Items)
            {
                item.ForeColor = Color.FromArgb(64, 64, 64);
                item.Font = new Font("微软雅黑", 14, FontStyle.Regular, GraphicsUnit.Pixel);
                item.Height = 30;
                item.TextAlign = ContentAlignment.MiddleLeft;
            }
        }

        private void dSkinPanel5_LayeredPaintEvent(object sender, PaintEventArgs e)
        {
            //使用红色虚线绘制边框
            Pen pen1 = new Pen(Color.Red, 2);
            pen1.DashStyle = System.Drawing.Drawing2D.DashStyle.DashDot;
            pen1.DashPattern = new float[] { 4f, 2f, 4f };
        }

        /// <summary>
        /// 菜单切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dSkinTabBar1_TabControlSelectedIndexChanged(object sender, DSkin.Controls.DSkinTabBarEventArgs e)
        {

        }

        private void dSkinPanel5_LayeredPaintEvent_1(object sender, PaintEventArgs e)
        {
            ControlPaint.DrawBorder(e.Graphics, ClientRectangle, Color.Ivory, ButtonBorderStyle.Dashed);
        }

        /// <summary>
        /// 账号配置菜单切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dSkinTabBar2_TabControlSelectedIndexChanged(object sender, DSkin.Controls.DSkinTabBarEventArgs e)
        {
            try
            {
                if (e.DSkinTabItem.Name.Equals("tabItemQiNiu"))
                {
                    var data = db.SelectWhere(MTableName, new string[] { "*" }, new DbCompareEqual("Type", "1"));
                    while (data.Read())
                    {
                        txtQNBucketName.Text = data.GetString(0);
                        txtQNAccessKey.Text = data.GetString(1);
                        txtQNSecretKey.Text = data.GetString(2);
                        txtQNDomain.Text = data.GetString(3);
                    }
                    MType = 1;
                }
                else if (e.DSkinTabItem.Name.Equals("tabItemAliYun"))
                {
                    var data = db.SelectWhere(MTableName, new string[] { "*" }, new DbCompareEqual("Type", "2"));
                    while (data.Read())
                    {
                        txtALiBucketName.Text = data.GetString(0);
                        txtALiAccessKey.Text = data.GetString(1);
                        txtALiSecretKey.Text = data.GetString(2);
                        txtALiEndPoint.Text = data.GetString(3);
                    }
                    MType = 2;
                }
                else
                {
                    var data = db.SelectWhere(MTableName, new string[] { "*" }, new DbCompareEqual("Type", "3"));
                    while (data.Read())
                    {
                        txtTXBucketName.Text = data.GetString(0);
                        txtTXSecretID.Text = data.GetString(1);
                        txtTXSecretKey.Text = data.GetString(2);
                        txtTXEndPoint.Text = data.GetString(3);
                    }
                    MType = 3;
                }
            }
            catch (Exception)
            {
                DSkinMessageBox.Show("网络错误，请稍后再试", "异常提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #region 上传图片事件
        /// <summary>
        /// 拖动图片上传
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabPageUpload_DragEnter(object sender, DragEventArgs e)
        {
            try
            {
                e.Effect = e.Data.GetDataPresent(DataFormats.FileDrop) ? DragDropEffects.Link : DragDropEffects.None;
                //本地文件路径
                string filePath = ((Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();

            }
            catch (Exception)
            {
                DSkinMessageBox.Show("网络错误，请稍后再试", "异常提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 选择图片上传
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabPageUpload_Click(object sender, EventArgs e)
        {
            try
            {
                var file = new OpenFileDialog();
                file.Filter = @"图片(*.jpg,*.png,*.gif,*.bmp,*.svg,*.webp)|*.jpg;*png;*.gif;*.bmp;*.svg;*.webp|所有文件(*.)|*.*";
                if (file.ShowDialog() == DialogResult.OK)
                {
                    Invoke(new Action(delegate ()
                    {
                        QiNiuHelper.UploadFiles(db, file.FileName);
                        var msg = new FrmMsg("上传成功", file.FileName);
                        msg.Show();
                    }));
                }
            }
            catch (Exception)
            {
                DSkinMessageBox.Show("网络错误，请稍后再试", "异常提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion


        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                switch (MType)
                {
                    case 1:
                        int.Parse("asd");
                        db.Delete(MTableName, new DbCompareEqual("Type", "1"));

                        db.InsertIntoSpecific(MTableName,
                            new string[] { "BucketName", "AccessKey", "SecretKey", "Domain", "Type" },
                            new string[] { txtQNBucketName.Text.Trim(), txtQNAccessKey.Text.Trim(), txtQNSecretKey.Text.Trim(), txtQNDomain.Text.Trim(), "1" });

                        var result = QiNiuHelper.CheckAccount(txtQNAccessKey.Text, txtQNSecretKey.Text, txtQNDomain.Text);
                        if (result.Code == 401)
                        {

                        }
                        var msg = new FrmMsg("保存成功", "");
                        msg.Show();
                        break;
                    case 2:
                        db.Delete(MTableName, new DbCompareEqual("Type", "2"));

                        db.InsertIntoSpecific(MTableName,
                            new string[] { "BucketName", "AccessKey", "SecretKey", "Domain", "Type" },
                            new string[] { txtALiBucketName.Text.Trim(), txtALiAccessKey.Text.Trim(), txtALiSecretKey.Text.Trim(), txtALiEndPoint.Text.Trim(), "2" });
                        break;
                    default:
                        db.Delete(MTableName, new DbCompareEqual("Type", "3"));

                        db.InsertIntoSpecific(MTableName,
                            new string[] { "BucketName", "AccessKey", "SecretKey", "Domain", "Type" },
                            new string[] { txtTXBucketName.Text.Trim(), txtTXSecretID.Text.Trim(), txtTXSecretKey.Text.Trim(), txtTXEndPoint.Text.Trim(), "3" });
                        break;
                }
            }
            catch (Exception)
            {
                DSkinMessageBox.Show("网络错误，请稍后再试", "异常提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dSkinLabel17_Click(object sender, EventArgs e)
        {
            //调用系统默认的浏览器   
            System.Diagnostics.Process.Start("http://mpic.lzhaofu.cn");
        }

        /// <summary>
        /// 监听剪切板
        /// </summary>
        /// <param name="m"></param>
        protected override void DefWndProc(ref Message m)
        {
            #region MyRegion
            try
            {
                if (m.Msg != WM_CLIPBOARDUPDATE)
                {
                    base.DefWndProc(ref m);
                    return;
                }
                IDataObject iData = Clipboard.GetDataObject();
                if (iData != null)
                {
                    if (iData.GetDataPresent(DataFormats.Bitmap)) //截图
                    {
                        int.Parse("asd");

                        Image img = (Bitmap)iData.GetData(DataFormats.Bitmap);

                        var path = string.Format("{0}\\MPic", Application.StartupPath);
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        var imageName = DateTime.Now.ToString("MMddHHmmssfff") + ".png";
                        var savePath = string.Format("{0}\\{1}", path, imageName);
                        img.Save(savePath, ImageFormat.Png);
                        img.Dispose();

                        var data = db.SelectWhere(MTableName, new string[] { "*" }, new DbCompareEqual("Type", "1"));
                        while (data.Read())
                        {
                            Invoke(new Action(delegate ()
                            {
                                QiNiuHelper.UploadFiles(db, savePath);
                                var frmMsg = new FrmMsg("上传成功", "");
                                frmMsg.Show();
                            }));
                        }
                    }
                    else
                    {

                    }
                }
            }
            catch (Exception)
            {
                DSkinMessageBox.Show(this, "网络错误，请稍后再试", "异常提示", MessageBoxIcon.Error, false, MessageBoxButtons.OK);
            }
            #endregion
        }

        /// <summary>
        /// 加QQ好友
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQQChat_Click(object sender, EventArgs e)
        {
            //调用浏览器打开加QQ好友
            System.Diagnostics.Process.Start("tencent://AddContact/?fromId=45&fromSubId=1&subcmd=all&uin=762004031&website=mpic.lzhaofu.cn");
        }
    }
}
